<template>
  <div class="sanstyle">
    <!-- 左边 -->
    <div>
      <div class="ssl">
        <!--标题 B-->
        <div class="sstitle" style="padding-right: .35rem;">
          <div class="twz">
            <span class="dwz">设备列表</span>
            <br />
            <span class="xwz">Device list</span>
          </div>
        </div>
        <!--标题 E-->
        <div class="stjqy" style="margin-left: -.2rem;">
          <div class="bdbk" style="height: 55%">
            <!-- 七里海 -->
            <div class="btn_box">
              <div class="btn_radio">
                <input
                  type="radio"
                  value="识别框"
                  :checked="isChecked"
                  @click="toggleRadioButton"
                />
                <label for="识别框" class="txts">识别框</label><br />
              </div>
              <div class="righttop_foot">
                <el-table :data="tableData" style="width: 100%" height="100%">
                  <el-table-column prop="onLine" label="设备状态" width="">
                    <template #default="scope">
                      <div class="sxt">
                        <img
                          src="../../static/images/sxt.png"
                          alt=""
                          style="width: .2rem;height: .2rem;"
                        />
                        <span>{{
                          scope.row.deviceStatus == 1 ? "在线" : "离线"
                        }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="deviceName"
                    label="摄像头名称"
                    width=""
                  />
                  <el-table-column label="操作" width="">
                    <template #default="scope">
                      <img
                        src="../../static/images/jt.png"
                        alt=""
                        style="width: 0.26rem; height: 0.14rem; cursor: pointer"
                        @click="btn_bf(scope.row)"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
          <div style="height: 45%; position: relative">
            <div
              class="sstitle"
              style="padding-right: .35rem;margin-top: .2rem;"
            >
              <div class="twz">
                <span class="dwz">云台控制</span>
                <br />
                <span class="xwz">Pan-tilt control</span>
              </div>
            </div>
            <div class="yuntai_box" id="bar1">
              <div class="yuntai_top">
                <!-- 圆 -->
                <div class="round">
                  <div class="r1">
                    <img
                      src="../../static/images/shang.png"
                      alt=""
                      @mousedown.left="btn_direction('up', 'UP')"
                      @mouseup.left="btn_direction('stop')"
                    />
                  </div>
                  <div class="r3">
                    <img
                      src="../../static/images/zuo.png"
                      alt=""
                      @mousedown.left="btn_direction('left', 'LEFT')"
                      @mouseup.left="btn_direction('stop')"
                    />
                    <img
                      src="../../static/images/you.png"
                      alt=""
                      @mousedown.left="btn_direction('right', 'RIGHT')"
                      @mouseup.left="btn_direction('stop')"
                    />
                  </div>
                  <div class="r1">
                    <img
                      src="../../static/images/xia.png"
                      alt=""
                      @mousedown.left="btn_direction('down', 'DOWN')"
                      @mouseup.left="btn_direction('stop')"
                    />
                  </div>
                </div>
                <!-- 放大缩小 -->
                <div class="control">
                  <div
                    class="big tops"
                    @mousedown.left="btn_direction('zoomin', 'ZOOM_IN')"
                    @mouseup.left="btn_direction('stop')"
                  >
                    <img src="../../static/images/fd.png" alt="" />
                    <span style="margin-left: 0.05rem">放大</span>
                  </div>
                  <div
                    class="big"
                    @mousedown.left="btn_direction('zoomout', 'ZOOM_OUT')"
                    @mouseup.left="btn_direction('stop')"
                  >
                    <img src="../../static/images/sx.png" alt="" />
                    <span style="margin-left: 0.05rem">缩小</span>
                  </div>
                </div>
              </div>
              <!-- 线 -->
              <hr class="style1" />
              <div class="yuntao_footer">
                <div class="hm">
                  <span>画面选择</span>
                  <i
                    class="el-icon-full-screen"
                    :class="{ active: spilt == 1 }"
                    @click="changeGrid(1)"
                  ></i>
                  <i
                    class="el-icon-menu"
                    :class="{ active: spilt == 4 }"
                    @click="changeGrid(4)"
                  ></i>
                  <i
                    class="el-icon-s-grid"
                    :class="{ active: spilt == 6 }"
                    @click="changeGrid(9)"
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!--三栏布局E-->
      </div>
    </div>
    <!-- 右边 -->
    <div style="width: 73%;margin-left: 16px">
      <!-- 九宫格 -->
      <div class="a_left">
        <div
          v-for="i in spilt"
          :key="i"
          class="play-box"
          :style="liveStyle"
          @click="btn_xh(i)"
        >
          <div
            v-if="!videoUrl[i - 1]"
            style="color: #ffffff; font-size: 0.3rem; font-weight: bold;width: 100%;height: 100%;"
            :class="{ redborder: playerIdx == i - 1 }"
            class="no-video"
          >
            <span>{{ i }}</span>
          </div>
          <!-- AI识别 -->
          <div
            class="ai-box"
            style="width: 100%; height: 100%; border: none"
            v-if="videoUrl[i - 1] && AItxt == 'AI识别'"
            ref="playerRefs"
          >
            <iframe
              style="width: 100%; height: 100%; border: none"
              :src="
                'http://223.71.254.174:35008/detect_Stream/' +
                  (changeHikId ? changeHikId : hikId[i - 1])
              "
              @screenshot="shot"
              allowfullscreen="true"
            ></iframe>
            <div
              class="zhezhaoa"
              style="width: 100%; height: 100%; "
              :class="{ redborder: playerIdx == i - 1 }"
              @destroy="destroy"
            ></div>
          </div>
          <!-- 普通监控 -->
          <player
            ref="playerRefs"
            v-if="videoUrl[i - 1] && AItxt == '普通监控'"
            :videoUrl="changeVideo || videoUrl[i - 1]"
            fluent
            autoplay
            @screenshot="shot"
            @destroy="destroy"
            :class="{ redborder: playerIdx == i - 1 }"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import http from "../utils/http";
import api from "../utils/api";
import player from "../components/common/jessibuca.vue";
import * as axios from "axios";
export default {
  components: {
    player
  },
  data() {
    return {
      isChecked: false,
      AItxt: "普通监控",
      tableData: [],
      playerRefs: [],
      manageSite: "",
      spilt: 4,
      videoUrl: [""],
      playerIdx: 0, //激活播放器
      updateLooper: 0, //数据刷新轮训标志
      firstVariable: "",
      secondVariable: "",
      hikId: [""],
      changeHikId: "",
      changeVideo: ""
    };
  },
  created() {
    this.manageSite = sessionStorage.getItem("manageSite");
    this.getMonitorList();
  },
  computed: {
    liveStyle() {
      let style = { width: "100%", height: "100%" };
      switch (this.spilt) {
        case 4:
          style = { width: "50%", height: "50%" };
          break;
        case 9:
          style = { width: "33.3%", height: "33.3%" };
          break;
      }
      this.$nextTick(() => {
        for (let i = 0; i < this.spilt; i++) {
          const player = this.$refs.playerRefs;
          player && player[i] && player[i].updatePlayerDomSize();
        }
      });
      return style;
    }
  },
  watch: {
    // spilt(newValue) {
    //     console.log("切换画幅;" + newValue)
    //     let that = this
    //     for (let i = 1; i <= newValue; i++) {
    //         if (!that.$refs['player' + i]) {
    //             continue
    //         }
    //         this.$nextTick(() => {
    //             if (that.$refs['player' + i] instanceof Array) {
    //                 that.$refs['player' + i][0].resize()
    //             } else {
    //                 that.$refs['player' + i].resize()
    //             }
    //         })

    //     }
    //     window.localStorage.setItem('split', newValue)
    // },
    // '$route.fullPath': 'checkPlayByParam'
    spilt(newValue) {
      this.$nextTick(() => {
        for (let i = 1; i <= newValue; i++) {
          const players = this.playerRefs["player" + i];
          if (players) {
            if (Array.isArray(players)) {
              players[0].resize();
            } else {
              players.resize();
            }
          }
        }
      });
      window.localStorage.setItem("split", newValue);
    },
    "$route.fullPath": "checkPlayByParam"
  },
  destroyed() {
    clearTimeout(this.updateLooper);
  },
  methods: {
    toggleRadioButton() {
      this.isChecked = !this.isChecked;
      if (this.isChecked == false) {
        this.AItxt = "普通监控";
      } else {
        this.AItxt = "AI识别";
      }
    },
    // 摄像头列表
    async getMonitorList() {
      let res = await http.get(api.getAnimalMonitorListApi, {
        manageSite: this.manageSite
      });
      console.log(res , 'resssssssssss');
      if (res.data.code == 200) {
        this.tableData = res.data.data.humanBirdDevices;
        console.log(this.tableData , 'tableData');
      }
    },
    destroy(idx) {
      this.clear(idx.substring(idx.length - 1));
    },
    shot(e) {
      // send({code:'image',data:e})
      var base64ToBlob = function(code) {
        let parts = code.split(";base64,");
        let contentType = parts[0].split(":")[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
          type: contentType
        });
      };
      let aLink = document.createElement("a");
      let blob = base64ToBlob(e); //new Blob([content]);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = "截图";
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },

    clear(idx) {
      let dataStr = window.localStorage.getItem("playData") || "[]";
      let data = JSON.parse(dataStr);
      data[idx - 1] = null;
      window.localStorage.setItem("playData", JSON.stringify(data));
    },
    btn_bf(a) {
      let arr = JSON.parse(a.channelNumber);
      let deviceId = a.serialNumber;
      let channelId = arr[0].channelNumber;
      this.firstVariable = a.serialNumber;
      this.secondVariable = arr[0].channelNumber;
      if (this.spilt == 1) {
        this.btn_xh(1);
      }
      let hikIds = a.hikId;
      this.sendDevicePush({ hikIds });
      this.sendDevicePush1({ deviceId, channelId });
    },
    async sendDevicePush(itemData) {
      try {
        this.save(itemData);
        let hikIds = itemData.hikIds;
        let idxTmp = this.playerIdx;
        this.loading = true;
        this.hikId[idxTmp] = itemData.hikIds;
        const response = await axios.get(`/vis/detect_video/${hikIds}`);
        if (response.data.code === 200 && response.data.data) {
          let videoUrl =
            location.protocol === "https:"
              ? response.data.data.wss_flv
              : response.data.data.ws_flv;
          itemData.playUrl = videoUrl;
          this.setPlayUrl(videoUrl, idxTmp);
        } else {
          // this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
      } finally {
        this.loading = false;
      }
    },
    async sendDevicePush1(itemData) {
      try {
        this.save(itemData);
        let deviceId = itemData.deviceId;
        let channelId = itemData.channelId;
        console.log("通知设备推流1：" + deviceId + " : " + channelId);
        let idxTmp = this.playerIdx;
        this.loading = true;
        const response = await axios.get(
          `http://36.99.41.50/api/play/start/${deviceId}/${channelId}`
        );
        if (response.data.code === 0 && response.data.data) {
          let videoUrl =
            location.protocol === "https:"
              ? response.data.data.wss_flv
              : response.data.data.ws_flv;
          itemData.playUrl = videoUrl;
          this.setPlayUrl(videoUrl, idxTmp);
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
      } finally {
        this.loading = false;
      }
    },
    setPlayUrl(url, idx) {
      this.$set(this.videoUrl, idx, url);
      setTimeout(() => {
        window.localStorage.setItem("videoUrl", JSON.stringify(this.videoUrl));
      }, 100);
    },
    changeGrid(n) {
      if (this.spilt == n) return;
      if (n != 1) {
        this.changeVideo = "";
        this.changeHikId = "";
      }
      this.spilt = n;
      if (n == 1) {
        // btn_xh(1)
      } else {
        this.playerIdx = 0; //切换分屏数量后默认选中第一块分屏
      }
    },
    btn_xh(i) {
      this.playerIdx = i - 1;
      const regex = /\/(\d+)_(\d+)\.live\.flv/;
      if (this.videoUrl[this.playerIdx] !== undefined) {
        let matches = this.videoUrl[this.playerIdx].match(regex);
        if (matches && matches.length === 3) {
          // matches[1] 包含第一个数字
          // matches[2] 包含第二个数字
          const firstNumber = matches[1];
          const secondNumber = matches[2];
          // 保存到两个不同的变量中
          this.firstVariable = firstNumber;
          this.secondVariable = secondNumber;
        } else {
          // URL不匹配预期的格式
          console.error("URL格式不正确");
        }
      }
    },
    save(item) {
      let dataStr = window.localStorage.getItem("playData") || "[]";
      let data = JSON.parse(dataStr);
      data[this.playerIdx] = item;
      window.localStorage.setItem("playData", JSON.stringify(data));
    },
    async btn_direction(a) {
      let d = 255;
      const baseUrl = "http://36.99.41.50/api/ptz/control/";
      const url = `${baseUrl}${this.firstVariable}/${this.secondVariable}`;
      const params = {
        command: a,
        horizonSpeed: d,
        verticalSpeed: d,
        zoomSpeed: d
      };
      let res = await axios.post(url, null, { params: params });
    }
  }
};
</script>

<style scoped>
@import "../../static/css/Newmonitoring.css";
@import "../../static/css/map_monitoring.css";
</style>
<style>
.el-table {
  background: none;
  color: #fff;
}

.el-table tr {
  background: none;
}
.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  background: none !important;
}
.el-table th.el-table__cell {
  background: rgba(46, 255, 242, 0.2) !important;
  height: 0.38rem;
  border: none !important;
  border-bottom: none !important;
  text-align: center;
  color: #fff;
}

.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background: none;
}

.el-table td.el-table__cell {
  border: none !important;
  border-bottom: none !important;
  text-align: center;
}
.el-table__body-wrapper::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}

.el-table__body-wrapper::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 2px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(46, 255, 242, 0.6);
}

/* .el-date-editor.el-input {
  width: 100% !important;
}

.el-input {
  --el-input-bg-color: none;
  --el-input-border-color: rgba(102, 225, 252, 0.5);
}

:root {
  --el-bg-color-overlay: linear-gradient(180deg,
      #052548 0%,
      rgba(31, 80, 134, 0.4) 100%);
  --el-text-color-regular: #fff;
  --el-border-color-lighter: rgba(102, 225, 252, 0.5);
  --el-fill-color-light: none;
}

.el-date-picker {
  --el-datepicker-text-color: #fff;
}

.el-picker__popper {
  --el-datepicker-border-color: rgba(102, 225, 252, 0.5);
} */
</style>
